package com.weilaiwd.upload.web;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.ActionEnter;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;
import com.weilaiwd.common.web.BaseAction;
import com.weilaiwd.upload.util.Lang;

public class UploadAction extends BaseAction {
	
	static Prop prop = PropKit.use("config.properties");
	
	public void ueditor() {
		try {
			getRequest().setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String rootPath = getRequest().getSession().getServletContext().getRealPath("/");
		//解决session丢失的问题
		super.setCookie("JSESSIONID", getPara(), -1, "/");
		renderJson(new ActionEnter(getRequest(), rootPath).exec());
	}
	
	public void jquery() {
		List<UploadFile> list = getFiles("temp");
		String index1 = getPara("index1", "default");
		String index2 = getPara("index2", "default");
		
		String prefix = prop.get("path.prefix");
		String domain = prop.get("static.domain");
		
		String dir = prefix+index1+"/"+index2+"/";
		String url = domain+index1+"/"+index2+"/";
		JSONArray jsonArray = new JSONArray();
		for(UploadFile file:list) {
			String fileName = file.getFileName();
			String[] array = fileName.split("\\.");
			String suffix = array[array.length-1];
			String newName = Lang.getUUID()+"."+suffix;;
			String path = dir+newName;
			url = url+newName;
			File target = new File(path);
			JSONObject json = new JSONObject();
			try {
				FileUtils.moveFile(file.getFile(), target);
				json.put("name", file.getParameterName());
				json.put("url", url);
				jsonArray.add(json);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		renderJson(jsonArray.toString());
	}

}
